package com.zyk.scaffold.oauth.config.oauth.grant;

import com.zyk.scaffold.oauth.config.oauth.support.LocalUserDetailsService;
import com.zyk.scaffold.oauth.framework.OauthManager;
import com.zyk.scaffold.oauth.framework.domain.*;
import com.zyk.scaffold.oauth.framework.interfaces.ITokenGranter;
import com.zyk.scaffold.common.utils.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;

@Slf4j
public class RefreshTokenTokenGranter implements ITokenGranter {
    private String grantType = "refresh_token";
    private OauthManager oauthManager;
    private LocalUserDetailsService localUserDetailsService;
    public RefreshTokenTokenGranter(OauthManager oauthManager, LocalUserDetailsService localUserDetailsService) {
        log.info("RefreshTokenTokenGranter created!");
        this.oauthManager = oauthManager;
        this.localUserDetailsService = localUserDetailsService;
    }

    @Override
    public OauthContext grant(OauthRequest request) {
        String refreshTokenStr = request.getRefreshToken();
        AssertUtil.notEmptyString(refreshTokenStr, "refreshToken不能为空");
        RefreshToken refreshToken = oauthManager.getRefreshToken(refreshTokenStr);
        AssertUtil.notNull(refreshToken, "token不存在,登录失败");
        ClientDetails clientDetails = this.oauthManager.getClientDetailsService().loadClientDetailsByClientId(refreshToken.getClientId());
        AssertUtil.notNull(clientDetails, "客户端不存在,禁止登录");
        UserDetails userDetails = localUserDetailsService.loadTenantUserDetails(refreshToken.getAccount(), MapUtils.getString(refreshToken.getData(), "tenantCode"));
        AssertUtil.notNull(userDetails, "账号不存在,禁止登录");
        OauthContext oauthContext = new OauthContext(userDetails, request, clientDetails);
        return oauthContext;
    }

    @Override
    public String getGrantType() {
        return grantType;
    }
}
